﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;

namespace UPnP
{
    class Message
    {
        public Message(string req)
        {
            string[] p = req.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            if (p.Length > 0)
            {
                RequestLine = p[0].ToUpper();
                for (int i = 1; i < p.Length; i++)
                {
                    int c = p[i].IndexOf(':');
                    if (c > -1 && c + 1 < p[i].Length)
                    {
                        string key = p[i].Substring(0, c).ToLower();
                        string value = p[i].Substring(c + 1).Trim();
                        Headers.Add(new KeyValuePair<string, string>(key, value));
                    }
                }
            }
        }

        public string GetXml()
        {
            if (Location.Trim() == "")
            {
                return "";
            }
            WebClient wc = new WebClient();
            return wc.DownloadString(Location);
        }

        public string Header(string key)
        {
            key = key.ToLower();
            foreach (KeyValuePair<string, string> kv in Headers)
            {
                if (kv.Key == key)
                {
                    return kv.Value;
                }
            }
            return "";
        }

        public string NT { get { return Header("nt"); } }
        public string NTS { get { return Header("nts"); } }
        public string Server { get { return Header("server"); } }
        public string UniqueServiceIdentifier { get { return Header("usn"); } }
        public string Location { get { return Header("location"); } }
        public string RemoteEndPoint { get; set; }

        public string RequestLine { get; set; }
        private List<KeyValuePair<string,string>> Headers = new List<KeyValuePair<string,string>>();
    }
}
